<?php
/**
 * Created by PhpStorm.
 * User: jiayanxiu
 * Date: 15/9/9
 * Time: 11:40
 */
class GoodsApp extends MallbaseApp {

    /**
     * @var CommonApp
     */
    private $common;

    /**
     * 初始化
     */
    public function __construct() {
        $this->common = new CommonApp();
    }

    /**
     * 添加商品浏览信息
     * @author jyx
     * @date 2015/09/08
     */
    public function addGoodsViews() {
        $action = '添加商品浏览信息';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法操作！');
        }
        $goods_id = $this->get_gp('goods_id', 'P');
        $goods_id = $goods_id ? intval($goods_id) : 0;
        $user_id = $this->checkLogin();
        if (!$user_id) {
            $this->ajax_return(ERROR_LOGIN, '请您进行登陆！');
        }
        $model = m('goods');
        $data = $model->get_info($goods_id);
        if(empty($data)){
            $this->ajax_return(FLAG_ERROR, '不存在的商品信息！');
        }
        $model->begin();
        //如果用户登陆了则插入或更新商品浏览信息
        if ($user_id) {
            $source = S_IOS;
            $time = time();
            $sql = "SELECT goods_id FROM ".DB_PREFIX."goods_views WHERE goods_id={$goods_id} AND user_id={$user_id} AND source={$source}";
            $info = $model->getRow($sql);
            if ($info) {
                $sql = "UPDATE ".DB_PREFIX."goods_views SET update_time={$time} WHERE goods_id={$goods_id} AND user_id = {$user_id} AND source={$source}";
                $flag = $model->query($sql);
                if ($flag === false) {
                    $model->rollback();
                    $this->ajax_return(FLAG_ERROR, '更新商品浏览记录信息失败！');
                }
            } else {
                $sql = "INSERT INTO ".DB_PREFIX."goods_views (goods_id,user_id,add_time,source) VALUES ({$goods_id},{$user_id},{$time},$source)";
                $flag = $model->query($sql);
                if ($flag === false) {
                    $model->rollback();
                    $this->ajax_return(FLAG_ERROR, '插入商品浏览记录信息失败！');
                }
            }
        }
        //更新商品的浏览量
        $sql = "SELECT goods_id FROM ".DB_PREFIX."goods_statistics WHERE goods_id={$goods_id}";
        if ($model->getRow($sql)) {
            $sql = "UPDATE ".DB_PREFIX."goods_statistics SET views=views+1 WHERE goods_id={$goods_id}";
            $rs = $model->query($sql);
            if ($rs === false) {
                $model->rollback();
                $this->ajax_return(FLAG_ERROR, '更新商品浏览量信息失败！');
            }
        } else {
            $sql = "INSERT INTO ".DB_PREFIX."goods_statistics (goods_id,views) VALUES ({$goods_id},1)";
            $rs = $model->query($sql);
            if ($rs === false) {
                $model->rollback();
                $this->ajax_return(FLAG_ERROR, '插入商品浏览量信息失败！');
            }
        }
        $model->commit();
        $this->ajax_return(FLAG_OK, '');
    }

    /**
     * 商品详情信息
     * @author jyx
     * @date 2015/07/20
     * 1.2版本使用
     */
    public function detail() {
        $action = '商品详情信息';
        setLogParameter($action);
        $version = strtoupper($_SERVER['HTTP_VERSION']);
        $this->check_method('GET');
        $user_id  = $this->checkLogin();
        $goods_id = $this->get_gp('goods_id', 'G');
        $goods_id = $goods_id ? intval($goods_id) : 0;
        if (!$goods_id) {
            $this->ajax_return(FLAG_ERROR, '商品id不正确！');
        }
        //获取商品信息,同时查询出此商品关注的总数量。
        $domain = get_domain();
        $model = m('goods');
        $sql = "SELECT g.goods_id,g.store_id,g.goods_name,g.introduction,g.description,g.cate_id,g.cate_name,g.is_act,
            g.default_image,g.price,g.discount_price,g.tags,g.act_start_time,g.act_end_time,g.spec_name_1,g.spec_name_2,
            g.detail_url,g.currency,g.source,g.activity_name,gs.collects,gs.base_collects,gs.sales,gs.base_sales,gs.comments,s.store_name,
            s.iphone_banner,s.store_logo,s.collects as scollects FROM ".DB_PREFIX."goods g LEFT JOIN ".DB_PREFIX."store s
            ON g.store_id=s.store_id LEFT JOIN ".DB_PREFIX."goods_statistics gs ON g.goods_id=gs.goods_id
            WHERE g.goods_id={$goods_id} AND g.if_examine=1 AND g.if_finance=1 AND g.if_show=1 AND g.closed=0 LIMIT 1";
        $data = $model->getRow($sql);
        if (!$data) {
            $this->ajax_return(FLAG_ERROR, '商品正在等待审核！');
        }
        //商品详情连接
        // @TODO 测试环境切换到线上环境时,需要切换这两行注释
        $data ['detail_uri'] ="http://vpn-m.herxi.com/index.php?c=index&a=graphicDetails&id={$data['goods_id']}";

        $data['collects'] = intval($data['collects'] + $data['base_collects']);
        $data['sales']  = intval($data['sales'] + $data['base_sales']);
        $data['comments'] = $data['comments'] ? intval($data['comments']) : 0;
        //是否是优惠活动
        $data['discount'] = $this->common->isAct($data);
        $data['description'] = htmlspecialchars_decode(stripcslashes($data['description']));
        $data["store_logo"] = $data["store_logo"] ? QINIU_URL.$data["store_logo"].STORE_LOGO : $domain.'/'.Conf::get('default_store_logo');
        $data['follow'] = $user_id ? $this->common->getRelationShip($user_id, $goods_id) : 0;//用户是否关注此商品
        $data['default_image'] = $this->common->isMySelfImage($data['default_image'], GOODS_IMG);
        if($user_id){
            //获取用户头像的信息
            $sql = "SELECT portrait FROM ".DB_PREFIX."member WHERE user_id={$user_id}";
            $tmp = $model->getRow($sql);
            $data['portrait'] = $tmp['portrait'] ? (substr($tmp['portrait'],0,7)!='http://' && substr($tmp['portrait'],0,8)!='https://' && $tmp['portrait'] ? QINIU_URL.$tmp['portrait'] : $tmp['portrait']) : '';
        } else {
            $data['portrait'] = '';
        }

        //查询出商品的总库存数
        $sql = "SELECT SUM(`stock`) total_stock FROM ".DB_PREFIX."goods_spec WHERE goods_id={$goods_id}";
        $tmp[0] = $model->getRow($sql);
        $data['allstock'] = $tmp[0]['total_stock'] ? intval($tmp[0]['total_stock']) : 0;

        //当前店铺的宝贝数
        $sql = "SELECT COUNT(goods_id) as total_count FROM ".DB_PREFIX."goods WHERE store_id={$data['store_id']}
            AND if_examine=1 AND if_finance=1 AND if_show=1 AND closed=0";
        $tmp[1] = $model->getRow($sql);
        $data['total_count'] = $tmp[1]['total_count'];

        //获取当前店铺的总销量
        $sql = "SELECT goods_id FROM ".DB_PREFIX."goods WHERE store_id={$data['store_id']}";
        $sql = "SELECT SUM(sales) AS total_sales,SUM(base_sales) AS base_sales FROM ".DB_PREFIX."goods_statistics WHERE goods_id IN ({$sql})";
        $tmp[2] = $model->getRow($sql);
        $data['allsale'] = $tmp[2]['total_sales'] + $tmp[2]['base_sales'];
        //获取同一款商品的其它图片
        $sql = 'SELECT image_id,thumbnail,image_url FROM '.DB_PREFIX."goods_image WHERE goods_id={$goods_id} ORDER BY sort_order ASC";
        $info = $model->getAll($sql);
        if ($info) {
            foreach ($info as $key=>$val) {
                $val['image_url'] = $this->common->isMySelfImage($val['image_url'], GOODS_IMG);
                $val['thumbnail'] = $this->common->isMySelfImage($val['thumbnail'], GOODS_IMG);//新版本把这个字段去掉,1.4上线后去掉
                $data['image'][$key] = $val;
            }
        }
        //获取商品扩展的属性信息
        //判断版本
        if($version == 1.4) {
            $spec = $temp = array();
            $sql = 'SELECT spec_id,goods_id,spec_1,spec_2,spec,price,stock,sku,discount_spec_price,is_show_discount FROM ' . DB_PREFIX . "goods_spec WHERE goods_id={$goods_id}";
            $spec = $model->getAll($sql);
            if ($spec) {
                foreach ($spec as $key => $val) {
                    $temp[$val['spec_1']][] = $val;
                }
            }
            $data['spec'] = $temp;
        }else{
            $sql = 'SELECT spec_id,goods_id,spec_1,spec_2,spec,price,stock,sku,discount_spec_price,is_show_discount FROM ' . DB_PREFIX . "goods_spec WHERE goods_id={$goods_id}";
            $da = $model->getAll($sql);
            if($da[0]['spec']){
                $arr =array();
                foreach($da as &$val){
                    //对规格进行编译
                    $val['spec'] = json_decode(urldecode($val['spec']),true);
                    //将规格与对应的id进行联系
                    foreach ($val['spec'] as $key => $value) {
                        $arr[$value['name']][$value['value']][] = $val['spec_id'];
                    }
                }
                //print_r($arr);
                //根据需求添加返回参数的集合
                $arrs =$arr;
                foreach($arrs as $k=>$value){
                    $arrs[$k]=array_keys($value);
                }
                //查询与商品相关联的规格id
                $sql="SELECT * FROM ".DB_PREFIX."goods_spec WHERE goods_id={$goods_id}";
                $dat=$model->getAll($sql);
                foreach($dat as $value){
                    unset($value['spec']);
                    $result [ $value ['spec_id'] ] = $value;
                }
                $data['spec'] =$arr;
                $data ['specs']= $result;
                $data['key'] = $arrs;
            }else{
                $sql="SELECT * FROM ".DB_PREFIX."goods_spec WHERE goods_id={$goods_id}";
                $dat=$model->getAll($sql);
                foreach($dat as $value){
                    $data ['specs']=$value;
                }
            }
        }

        //查出同一个分类下，同一个品牌下，销售量最高的5个商品
        $sql = "SELECT g.goods_id,g.goods_name,g.price,g.introduction,g.default_image,g.currency,g.source,g.is_act,g.discount_price,
                g.act_start_time,g.act_end_time,gs.collects,gs.base_collects,gs.sales,gs.base_sales FROM ".DB_PREFIX."goods g
                LEFT JOIN ".DB_PREFIX."goods_statistics gs ON gs.goods_id=g.goods_id
                WHERE g.cate_id={$data['cate_id']} AND g.store_id={$data['store_id']} AND g.if_examine = 1
                AND g.if_finance = 1 AND g.if_show = 1 AND g.closed = 0 ORDER BY gs.sales DESC LIMIT 5";
        $love_goods = $model->getAll($sql);
        foreach ($love_goods as $key => $val) {
            $val['collects'] = $val['collects'] + $val['base_collects'];
            $val['sales'] = $val['sales'] + $val['base_sales'];
            $val['discount'] = $this->common->isAct($val);
            $val['follow'] = $user_id ? $this->common->getRelationShip($user_id, $val['goods_id']) : 0;//是否关注此商品
            $val['default_image'] = $this->common->isMySelfImage($val['default_image'], GOODS_IMG);//是否是本网站的图片
            $data["enjoy"][] = $val;
        }
        //获取购物车中所有商品的数量
        if ($user_id) {
            $sql = "SELECT SUM(quantity) AS quantity FROM ".DB_PREFIX."cart WHERE user_id={$user_id}";
            $tmps = $model->getRow($sql);
            $data['cart_quantity'] = $tmps['quantity'] ? intval($tmps['quantity']) : 0;
        } else {
            $data['cart_quantity'] = 0;
        }
        // 获取评论相关信息
        $count = $model->getRow("SELECT COUNT(id) AS num FROM ".DB_PREFIX."comments WHERE goods_id='{$goods_id}' and type=1 and if_examine=1 and if_show=1");
        $data['discuss']['number'] = (int)$count['num'];
        $discuss = $model->getAll("SELECT a.content,a.add_time,b.user_name,b.nickname,b.portrait FROM ".DB_PREFIX."comments AS a INNER JOIN ".DB_PREFIX."member AS b ON (a.user_id = b.user_id) WHERE a.goods_id='{$goods_id}' and a.type=1 and a.if_examine=1 and a.if_show=1 ORDER BY a.id DESC LIMIT 2");
        foreach($discuss as $v){
            $data['discuss']['list'][] = array(
                'user_name' => $v['user_name'] ? $v['user_name'] : $v['nickname'],
                'portrait' => $v['portrait'] ? substr($v['portrait'],0,7)!="http://" && substr($v['portrait'],0,8)!="https://" ? QINIU_URL.$v['portrait'] : $v['portrait'] : '',
                'content' => $v['content'],
                'add_time' => $v['add_time']
            );
        }
        $this->ajax_return(FLAG_OK, '', $data);
    }
















}